package logic

import (
	"context"
	"furniture/furniturerpc/furniturerpc"
	"furniture/furniturerpc/internal/svc"
	"furniture/models/mysql"
	"github.com/zeromicro/go-zero/core/logx"
)

type FurnitureAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewFurnitureAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FurnitureAddLogic {
	return &FurnitureAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *FurnitureAddLogic) FurnitureAdd(in *furniturerpc.FurnitureAddRequest) (*furniturerpc.FurnitureAddResponse, error) {
	// todo: add your logic here and delete this line

	begin := mysql.DB.Debug().Begin()

	var class mysql.Class
	begin.Where("name=?", in.ClassName).Find(&class)
	if class.ID == 0 {
		class = mysql.Class{
			Name: in.ClassName,
		}
		err := begin.Create(&class).Error

		if err != nil {
			begin.Rollback()
			return nil, err
		}
	}

	var brand mysql.Brand
	begin.Where("name=?", in.BrandName).Find(&brand)

	if brand.ID == 0 {
		brand = mysql.Brand{
			Name: in.BrandName,
		}
		err := begin.Create(&brand).Error

		if err != nil {
			begin.Rollback()
			return nil, err
		}
	}

	furniture := mysql.Furniture{
		Title:   in.Title,
		BrandId: int64(brand.ID),
		ClassId: int64(class.ID),
	}
	err := begin.Create(&furniture).Error

	if err != nil {
		begin.Rollback()
		return nil, err
	}

	begin.Commit()
	return &furniturerpc.FurnitureAddResponse{
		FurnitureId: int64(furniture.ID),
	}, nil
}
